package com.zhp.context;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.function.Supplier;

/**
 * @author zhanghp
 * @since 2024/5/20 17:51
 */
public class LazyExpireInstance {


    private static final Map<Object, TimedValueInfo<Object>> timedMap = new HashMap<>();





    public static Map<Object, TimedValueInfo<Object>> get(){
        return timedMap;
    }

    public static <K,V> V computeIfAbsent(K key, Supplier<V> value, Duration duration) {
        //todo: lru 防止容量溢出
        TimedValueInfo<Object> objectTimedValueInfo = timedMap.get(key);
        if (objectTimedValueInfo != null && objectTimedValueInfo.expireTime > System.currentTimeMillis()) {
            return (V)objectTimedValueInfo.value;
        }
        V ans = value.get();
        PriorityQueue<String> strings = new PriorityQueue<>();
        timedMap.put(key, new TimedValueInfo<Object>(ans, System.currentTimeMillis() + duration.toMillis()));
        return ans;
    }

    @Data
    @AllArgsConstructor
    private static class TimedValueInfo<V> {
        private V value;

        private long expireTime;
    }

}
